<?php
define('SYSADMIN', 1);
define('MANAGER', 5);

$project_id = intval( dPgetParam( $_GET, 'project_id', 0 ) );

// check permissions for this record
$perms =& $AppUI->acl();
$canRead = $perms->checkModuleItem( $m, 'view', $project_id );

if (!$canRead) {
	$AppUI->setMsg('Access denied', UI_MSG_ERROR);
	$AppUI->redirect();
}

// retrieve any state parameters
if (isset( $_GET['tab'] )) {
	$AppUI->setState( 'ProjVwTab', $_GET['tab'] );
}
$tab = $AppUI->getState( 'ProjVwTab' ) !== NULL ? $AppUI->getState( 'ProjVwTab' ) : 0;

// check if this record has dependencies to prevent deletion
$msg = '';
$obj = new CProject();
// Now check if the proect is editable/viewable.
$denied = $obj->getDeniedRecords($AppUI->user_id);
if (in_array($project_id, $denied)) {
	$AppUI->setMsg('Access denied', UI_MSG_ERROR);
	$AppUI->redirect();
}

$obj->load($project_id);
$isProjectManager = $AppUI->user_id == $obj->getManager();

$canEdit = $perms->checkModuleItem( $m, 'edit', $project_id ) && ($AppUI->user_type == SYSADMIN || $isProjectManager);
$canEditT = $obj->canCreateTasks();

$canDelete = $obj->canDelete( $msg, $project_id ) &&
			 ($AppUI->user_type == SYSADMIN || $AppUI->user_id == $obj->project_owner);

$canViewReport = ($isProjectManager) || ($AppUI->user_type <= MANAGER);

// get critical tasks (criteria: task_end_date)
$criticalTasks = ($project_id > 0) ? $obj->getCriticalTasks($project_id) : NULL;

// get ProjectPriority from sysvals
$projectPriority = dPgetSysVal( 'ProjectPriority' );
$projectPriorityColor = dPgetSysVal( 'ProjectPriorityColor' );

$working_hours = ($dPconfig['daily_working_hours']?$dPconfig['daily_working_hours']:8);

$q  = new DBQuery;
//check that project has tasks; otherwise run seperate query
$q->addTable('tasks');
$q->addQuery('COUNT(distinct tasks.task_id) AS total_tasks');
$q->addWhere('task_project = '.$project_id);
$hasTasks = $q->loadResult();
$q->clear();

// load the record data
// GJB: Note that we have to special case duration type 24 and this refers to the hours in a day, NOT 24 hours
if ($hasTasks) {
    $q->addTable('projects');
    $q->addQuery('company_name, CONCAT_WS(" ",contact_first_name,contact_last_name) user_name, projects.*,'
				.' SUM(t1.task_duration * t1.task_percent_complete'
				.' * IF(t1.task_duration_type = 24, '.$working_hours.', t1.task_duration_type))'
				.' / SUM(t1.task_duration * IF(t1.task_duration_type = 24, '.$working_hours.', t1.task_duration_type))'
				.' AS project_percent_complete');
    $q->addJoin('companies', 'com', 'company_id = project_company');
    $q->addJoin('users', 'u', 'user_id = project_owner');
    $q->addJoin('contacts', 'con', 'contact_id = user_contact');
    $q->addJoin('tasks', 't1', 'projects.project_id = t1.task_project');
    $q->addWhere('project_id = '.$project_id .' AND t1.task_id = t1.task_parent');
    $q->addGroup('project_id');
    $sql = $q->prepare();
}
else {
    $q->addTable('projects');
    $q->addQuery('company_name, CONCAT_WS(" ",contact_first_name,contact_last_name) user_name, projects.*, '
                 .'(0.0) AS project_percent_complete');
    $q->addJoin('companies', 'com', 'company_id = project_company');
    $q->addJoin('users', 'u', 'user_id = project_owner');
    $q->addJoin('contacts', 'con', 'contact_id = user_contact');
    $q->addWhere('project_id = '.$project_id);
    $q->addGroup('project_id');
    $sql = $q->prepare();
}
$q->clear();

$obj = null;
if (!db_loadObject( $sql, $obj )) {
	$AppUI->setMsg( 'Project' );
	$AppUI->setMsg( 'invalidID', UI_MSG_ERROR, true );
	$AppUI->redirect();
} else {
	$AppUI->savePlace();
}


// worked hours
// now milestones are summed up, too, for consistence with the tasks duration sum
// the sums have to be rounded to prevent the sum form having many (unwanted) decimals because of the mysql floating point issue
// more info on http://www.mysql.com/doc/en/Problems_with_float.html
if($hasTasks) {
	$q->addTable('task_log');
	$q->addTable('tasks');
	$q->addQuery('ROUND(SUM(task_log_hours),2)');
	$q->addWhere('task_log_task = task_id AND task_project = '.$project_id);
	$worked_hours = $q->loadResult();
	$worked_hours = rtrim($worked_hours, '.');

	// total hours
	// same milestone comment as above, also applies to dynamic tasks
	$q->addTable('tasks');
	$q->addQuery('ROUND(SUM(task_duration),2)');
	$q->addWhere('task_project = '.$project_id.' AND task_duration_type = 24 AND task_dynamic != 1');
	$days = $q->loadResult();

	$q->addTable('tasks');
	$q->addQuery('ROUND(SUM(task_duration),2)');
	$q->addWhere('task_project = '.$project_id.' AND task_duration_type = 1 AND task_dynamic != 1');
	$hours = $q->loadResult();
	$total_hours = $days * $dPconfig['daily_working_hours'] + $hours;

	$q->addTable('tasks', 't');
	$q->addQuery('ROUND(SUM(t.task_duration*u.perc_assignment/100),2)');
	$q->addJoin('user_tasks', 'u', 't.task_id = u.task_id');
	$q->addWhere('t.task_project = '.$project_id.' AND t.task_duration_type = 24 AND t.task_dynamic != 1');
	$total_project_days = $q->loadResult();

	$q->addTable('tasks', 't');
	$q->addQuery('ROUND(SUM(t.task_duration*u.perc_assignment/100),2)');
	$q->addJoin('user_tasks', 'u', 't.task_id = u.task_id');
	$q->addWhere('t.task_project = '.$project_id.' AND t.task_duration_type = 1 AND t.task_dynamic != 1');
	$total_project_hours = $q->loadResult();

	$total_project_hours = $total_project_days * $dPconfig['daily_working_hours'] + $total_project_hours;
	//due to the round above, we don't want to print decimals unless they really exist
	//$total_project_hours = rtrim($total_project_hours, "0");
}
else { //no tasks in project so "fake" project data
    $worked_hours = $total_hours = $total_project_hours = 0.00;
}
// get the prefered date format
$df = $AppUI->getPref('SHDATEFORMAT');

// create Date objects from the datetime fields
$start_date = intval( $obj->project_start_date ) ? new CDate( $obj->project_start_date ) : null;
$end_date = intval( $obj->project_end_date ) ? new CDate( $obj->project_end_date ) : null;
$actual_end_date = intval( $criticalTasks[0]['task_end_date'] ) ? new CDate( $criticalTasks[0]['task_end_date'] ) : null;
$style = (( $actual_end_date > $end_date) && !empty($end_date)) ? 'style="color:red; font-weight:bold"' : '';

// setup the title block
$titleBlock = new CTitleBlock( 'View Project' );

/*
// patch 2.12.04 text to search entry box
if (isset( $_POST['searchtext'] )) {
	$AppUI->setState( 'searchtext', $_POST['searchtext']);
}

$search_text = $AppUI->getState('searchtext') ? $AppUI->getState('searchtext'):'';
$titleBlock->addCell( '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' . $AppUI->_('Search') . ':' );
$titleBlock->addCell(
	'<input type="text" class="text" size="10" name="searchtext" onChange="document.searchfilter.submit();" value=' . "'$search_text'" .
	'title="'. $AppUI->_('Search in name and description fields') . '"/>', '',
	'<form action="?m=projects&a=view&project_id='.$project_id.'" method="post" id="searchfilter">', '</form>'
);
 */
$titleBlock->addCell();
$titleBlock->addButton( 'projects list', 'index.php?m=projects' );
$titleBlock->show();
?>
<script language="javascript">
<? if ($canEdit) { ?>
function doDeleteProject() {
	if (confirm( "<?=$AppUI->_('doDelete', UI_OUTPUT_JS).' '.$AppUI->_('Project', UI_OUTPUT_JS).'?'?>" )) {
		document.frmDelete.submit();
	}
}

function doMarkProject(c, s, d) {
	if (!confirm('Are you sure you want to mark this project as '+d+'?')) return;
	ajax.send('?m=projects&a=mark&suppressHeaders=1&project_id=<?=$project_id?>&status='+s, '',
		function(r) {
			if (r != 'OK') {
				var m = Control('idMsgDialog').create('div', 'popup', 'hidden');
				m.setAttribute('autohide', 'click');
				m.innerHTML = r;
				Dialog(m).show();
				return;
			}
			Control(c).hide();
			$('idProjectStatus').innerHTML = d.ucfirst();
		}
	);
}

function doShowControl()
{
	var m = $('idMainContents');
	var g = $('idGlass');
	var c = $('idControler');
	var d = $('idProjectControl');
	var p = Control(c).position();
	var w = new Contents();

	g.onclick = doHideControl;
	Control(g).resize(w.width, w.height);
	Control(g).show();

	Control(d).reparent(document.body);
	Control(d).show();
	Control(d).move(p.x + c.offsetWidth - d.offsetWidth, p.y + c.offsetHeight - m.scrollTop + 2);

	Table('idControlList').setNormalHover(0);
}

function doHideControl()
{
	Control('idProjectControl').hide();
	Control('idGlass').hide();
}

<? } ?>

function doShowMembers() {
	var d = Control('idProjectMembers').create('div', 'popup', 'hidden');
	if (d.innerHTML != '') {
		Dialog(d).show();
		return;
	}
	ajax.send('?m=projects&a=contacts&suppressHeaders=1&project_id=<?=$project_id?>','',
		function(r) {
			d.setAttribute('autohide', 'click');
			d.innerHTML = r;
			Dialog(d).show();
		}
	);
}
</script>
<? if ($canEdit) { ?>
<div id="idProjectControl" class="topper" style="visibility: hidden; border: 0px" onclick="doHideControl()">
<table id="idControlList" border="0" cellpadding="1" cellspacing="0" class="list" width="150px" style="cursor: pointer">
	<tr id="idCmdOrganize" class="second" onclick="go('?m=tasks&a=organize&project_id=<?=$project_id?>')">
		<td><?=$AppUI->_('Organize project')?></td>
		<td width="20px"><img src="images/task_arrange.gif"/></td>
	</tr>
	<? if ($obj->project_status < P_COMPLETED) { ?>
	<tr id="idCmdComplete" class="second" onclick="doMarkProject(this, <?=P_COMPLETED?>, 'completed')">
		<td><?=$AppUI->_('Complete project')?></td>
		<td width="20px"><img src="images/project_complete.gif"/></td>
	</tr>
	<? } ?>
	<? if ($obj->project_status < P_ARCHIVED) { ?>
	<tr id="idCmdArchive" class="second" onclick="doMarkProject(this, <?=P_ARCHIVED?>, 'archived')">
		<td><?=$AppUI->_('Archive project')?></td>
		<td width="20px"><img src="images/project_archive.gif"/></td>
	</tr>
	<? } ?>
	<? if ($canDelete) { ?>
	<tr id="idCmdDelete" class="second" onclick="doDeleteProject()">
		<td><?=$AppUI->_('Delete project')?></td>
		<td width="20px"><img src="images/project_delete.gif"/></td>
	</tr>
	<? } ?>
</table>
</div>

<form name="frmDelete" action="index.php?m=projects" method="post">
	<input type="hidden" name="dosql" value="do_project_aed" />
	<input type="hidden" name="del" value="1" />
	<input type="hidden" name="project_id" value="<?=$project_id?>" />
</form>
<? } ?>

<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
	<td class="tabon">
	<!-- style="border: outset #d1d1cd 1px;background-color:#<?=$obj->project_color_identifier?>" colspan="2"-->
	<?php
		$_SESSION['project_full_name'] =
		$project_full_name = '[ '.htmlspecialchars(@$obj->project_short_name, ENT_QUOTES).' ] '.$obj->project_name;
		echo /*'<font color="' . bestColor( $obj->project_color_identifier ) . '">*/
			'<b>'.$project_full_name.'</b>';//'</font>';
	?>
	</td>
	<td width="100%">&nbsp;</td>
</tr>
</table>
<table border="0" cellpadding="4" cellspacing="0" width="100%" class="infopanel">
<tr>
	<td class="status">Status:</td>
	<td id="idProjectStatus" nowrap="nowrap">
	<?
		echo $AppUI->_($pstatus[$obj->project_status]) . ' (';
		printf( '%.1f%%', $obj->project_percent_complete );
		echo ')';
	?>
	</td>
	<td><b><?=$AppUI->_('Priority')?>:</b></td>
	<td nowrap="nowrap"><!-- style="background-color:<?=$projectPriorityColor[$obj->project_priority]?>"-->
		<?=ucfirst($AppUI->_($projectPriority[$obj->project_priority]))?>
	</td>
	<td>&nbsp;</td>
	<td><b><?=$AppUI->_('Manager')?>:</b></td>
	<td nowrap="nowrap"><a href="javascript:User(<?=$obj->project_owner?>).show()"><?=$obj->user_name?></a></td>
	<td>&nbsp;</td>
	<td nowrap="nowrap"><b><?=$AppUI->_('Customer')?>:</b></td>
	<?php if ($perms->checkModuleItem( 'companies', 'access', $obj->project_company )) {?>
	<td width="100%"><a href="javascript:Company(<?=$obj->project_company?>).show()"><?=htmlspecialchars($obj->company_name, ENT_QUOTES)?></a></td>
	<?php } else {?>
	<td width="100%"><?=htmlspecialchars( $obj->company_name, ENT_QUOTES) ?></td>
	<?php }?>
	<td width="100%">
	</td>
	<td nowrap="nowrap">
	<?
		showIconLink( 'images/project_members.gif', 'js:doShowMembers()', 'Members' );
		echo '&nbsp;';
		if ($canViewReport) {
			showIconLink( 'images/project_report.gif', "?m=projects&a=reports&project_id=$project_id", 'Report' );
			echo '&nbsp;';
		}
		if ($canEdit) {
			showIconLink('images/project_edit.gif', "index.php?m=projects&a=addedit&project_id=$project_id", 'Edit');
			echo '&nbsp;';
			showIconLink('images/project_control.gif', 'js:doShowControl()', 'Manage', 'id="idControler"');
			echo '&nbsp;';
		}
	?>
	</td>
</tr>
</table>
<table border="0" cellpadding="0" cellspacing="4" width="100%" class="subinfopanel">
<tr style="background-color: white">
	<td width="50%" valign="top" style="background-color: white">
		<table width="100%" border="0" cellpadding="2" cellspacing="0" class="list">
			<tr><td colspan="6"><b><?=$AppUI->_('Date')?>:</b></td></tr>
			<tr class="second">
				<td align="right"><?=$AppUI->_('Start')?></td>
				<td class="value"><? echo $start_date ? $start_date->format( $df ) : '-'?></td>
				<td align="right"><?=$AppUI->_('Target End')?></td>
				<td><? echo $end_date ? $end_date->format( $df ) : '-'?></td>
				<td align="right"><?=$AppUI->_('Actual End')?></td>
				<td>
				<?
					if ($project_id > 0) {
						echo $actual_end_date ? '<a href="?m=tasks&a=view&task_id='.$criticalTasks[0]['task_id'].'">' : '';
						echo $actual_end_date ? '<span '. $style.'>'.$actual_end_date->format( $df ).'</span>' : '-';
						echo $actual_end_date ? '</a>' : '';
					} else {
						echo '<div title="'.$AppUI->_('Dynamically calculated').'">~</div>';
					}
				?>
				</td>
			</tr>
		</table>
	</td>
	<td width="50%" valign="top" style="background-color: white">
		<table width="100%" border="0" cellpadding="2" cellspacing="0" class="list">
			<tr>
				<td colspan="6"><b><?=$AppUI->_('Project time')?>:</b></td>
			</tr>
			<tr class="second">
				<td align="right" nowrap><?=$AppUI->_('Worked')?></td>
				<td align="center"><?=$worked_hours ? $worked_hours: 0?>h</td>
				<td align="right" nowrap><?=$AppUI->_('Planning')?></td>
				<td align="center"><?=$total_hours ? $total_hours : 0?>h</td>
				<td align="right" nowrap><?=$AppUI->_('Total')?></td>
				<td align="center"><?=$total_project_hours ? $total_project_hours : 0?>h</td>
			</tr>
		</table>
	</td>
</tr>
<tr id="detail" style="display: none; visibility: hidden">
	<td>
		<table cellspacing="1" cellpadding="2" border="0" width="100%" class="list">
		<tr>
			<td align="right" nowrap><?=$AppUI->_('Type')?>:</td>
			<td width="100%"><?=$AppUI->_($ptype[$obj->project_type])?></td>
		</tr>
		<tr>
			<td align="right" nowrap><?=$AppUI->_('Target Budget')?></td>
			<td><?=$dPconfig['currency_symbol'] ?><?=@$obj->project_target_budget?></td>
		</tr>
		<tr>
			<td align="right" nowrap="nowrap"><?=$AppUI->_('URL')?></td>
			<td><a href="<?=@$obj->project_url?>" target="_new"><?=@$obj->project_url?></A></td>
		</tr>
		<tr class="second">
			<td align="right" nowrap="nowrap"><?=$AppUI->_('Staging URL')?></td>
			<td><a href="<?=@$obj->project_demo_url?>" target="_new"><?=@$obj->project_demo_url?></a></td>
		</tr>
		<tr>
			<td valign="top" align="right">
			<?=$AppUI->_('Description')?>
			</td>
			<td>
				<?=str_replace( chr(10), '<br/>', $obj->project_description) ?>&nbsp;
			</td>
		</tr>
		<!--tr>
			<td>
			<?php
				require_once('classes/CustomFields.class.php');
				$custom_fields = new CustomFields( $m, $a, $obj->project_id, 'view' );
				$custom_fields->printHTML();
			?>
			</td>
		</tr-->

		<?php
		$q  = new DBQuery;
		$q->addTable('departments', 'a');
		$q->addTable('project_departments', 'b');
		$q->addQuery('a.dept_id, a.dept_name, a.dept_phone');
		$q->addWhere('a.dept_id = b.department_id and b.project_id = '.$project_id);
		$depts = $q->loadHashList('dept_id');
		if (count($depts) > 0) {
		?>
		    <tr>
		    	<td><strong><?=$AppUI->_('Departments')?></strong></td>
		    </tr>
		    <tr class="second">
		    	<td>
		    		<?php
		    			foreach($depts as $dept_id => $dept_info){
		    				echo '<div>'.$dept_info['dept_name'];
		    				if($dept_info['dept_phone'] != ''){
		    					echo '( '.$dept_info['dept_phone'].' )';
		    				}
		    				echo '</div>';
		    			}
		    		?>
		    	</td>
		    </tr>
	 	<?php } ?>
		</table>
	</td>
</tr>
</table>

<?php
$tabBox = new CTabBox( "?m=projects&a=view&project_id=$project_id", $tab );
$query_string = "?m=projects&a=view&project_id=$project_id";

if ($perms->checkModule('tasks', 'view')) {
	$tabBox->add( 'tasks', 'Tasks', 'tasks' );
	$tabBox->add( 'vw_logs', 'Task Logs' );
	$tabBox->add( 'viewgantt', 'Gantt Chart', 'tasks' );
}
/*
if ($perms->checkModule('forums', 'view'))
	$tabBox->add( 'vw_forums', 'Forums' );
*/
$tabBox->add( 'vw_files', 'Files' );

$tabBox->loadExtras($m);
$f = 'all';
$min_view = true;

$tabBox->show();
?>
